<template>
  <!-- 输入框 -->
  <div class="health_clock">
    <el-row :gutter="10" class="mb-10">
      <el-col :span="24"   >
        <el-row>
          <el-col :span="6" :xs="6">
            <el-input
              v-model.trim="username"
              placeholder="请输入用户名"
              suffix-icon="Search"
              @keyup.enter="load"
              @keyup.esc="username = ''"
            />
          </el-col>
          <el-col :span="6" :xs="6">
            <el-input
              v-model.trim="phone"
              placeholder="请输入电话"
              suffix-icon="Iphone"
              class="ml-5"
              @keyup.enter="load"
              @keyup.esc="phone = ''"
          /></el-col>
          <el-col :span="12" :xs="12">
            <el-button class="ml-12" type="primary" @click="load"
              >搜索</el-button
            >
            <el-button type="primary" @click="clears">重置</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 按钮 -->
    <el-row class="mb-10">
      <el-col :span="24">
        <el-button type="primary" @click="handleadd"
          >新增<el-icon class="ml-5" size="20px"><CirclePlus /></el-icon
        ></el-button>
        <el-popconfirm
          width="220"
          confirm-button-text="确定"
          cancel-button-text="我再想想"
          icon="InfoFilled"
          icon-color="red"
          title="您确定批量删除这些数据吗?"
          @confirm="delBatch"
          ><template #reference>
            <el-button type="danger"
              >批量删除<el-icon class="ml-10" size="20px"><Remove /></el-icon
            ></el-button> </template
        ></el-popconfirm>
        <el-upload
          class="upload_file ml-12 mr-12"
          :action="'http://' + serverIp + ':9090/healthclock/import'"
          :show-file-list="false"
          accept=".xlsx"
          :on-success="handleExcelImportSuccess"
          :on-error="handleExcelImportError"
        >
          <el-button type="primary">
            导入<el-icon class="ml-5" size="20px"><Upload /></el-icon>
          </el-button>
        </el-upload>
        <el-button type="primary" @click="exp"
          >导出<el-icon class="ml-5" size="20px"><Download /></el-icon
        ></el-button>
      </el-col>
    </el-row>

    <!-- 表单 -->
    <div class="user_table mr-12">
      <!--selection-change 当选择项发生变化时会触发该事件 -->
      <el-table
        :data="tableData"
        height="100%"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column prop="clockId" label="id" width="70" sortable fixed />
        <el-table-column prop="username" label="用户名" width="120" fixed />
        <el-table-column prop="sex" label="性别" width="55" />
        <el-table-column prop="age" label="年龄" width="55" />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column prop="morningTemp" label="早上体温" width="90" />
        <el-table-column prop="afternoonTemp" label="中午体温" width="90" />
        <el-table-column prop="nightTemp" label="晚上体温" width="90" />
        <el-table-column prop="symptom" label="症状" width="90" />
        <el-table-column prop="recentHome" label="近期所在地" width="100" />
        <el-table-column prop="riskZone" label="风险区" width="85">
          <template v-slot:default="scope">
            <el-tag
              :type="
                scope.row.riskZone === '高风险'
                  ? 'danger'
                  : scope.row.riskZone === '中风险'
                  ? 'warning'
                  : ''
              "
              >{{ scope.row.riskZone }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="recentZone" label="途径地区" width="200" />
        <el-table-column
          fixed="right"
          prop="healthStatus"
          label="健康状态"
          min-width="85px"
        >
          <template v-slot:default="scope">
            <el-tag
              :type="scope.row.healthStatus === '不健康' ? 'danger' : 'success'"
              >{{ scope.row.healthStatus }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column fixed="right" min-width="195" label="操作">
          <template v-slot:default="scope">
            <el-button type="success" @click="handleEdit(scope.row)"
              >编辑<el-icon class="ml-5"><Edit /></el-icon
            ></el-button>

            <!-- 气泡确认框 删除确认框 -->
            <el-popconfirm
              width="220"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="InfoFilled"
              icon-color="red"
              title="您确定删除吗?"
              @confirm="del(scope.row.clockId)"
            >
              <template #reference>
                <el-button type="danger"
                  >删除<el-icon class="ml-5"><Delete /></el-icon
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="pageNum"
        v-model="pageSize"
        :page-sizes="[2, 5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :small="small"
        :disabled="disabled"
        :background="background"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="健康打卡"
      width="45%"
      draggable
    >
      <el-form
        label-width="auto"
        :rules="rules"
        :model="form"
        ref="formRef"
        status-icon
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model.trim="form.username"
                autocomplete="off"
                placeholder="请输入用户名"
                size="large"
                clearable
              />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="form.sex">
                <el-radio label="女" size="large" border>女</el-radio>
                <el-radio label="男" size="large" border>男</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input
                v-model.trim="form.age"
                autocomplete="off"
                placeholder="请输入"
                size="large"
                clearable
              />
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input
                v-model.trim="form.phone"
                autocomplete="off"
                placeholder="请输入电话"
                size="large"
                clearable
              />
            </el-form-item>
            <el-form-item label="途径地区">
              <el-input
                v-model.trim="form.recentZone"
                type="textarea"
                placeholder="请输入途径地区&#10;输入格式如下：某地->某地->某地..."
                clearable
                rows="7"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="早上体温" prop="morningTemp">
              <el-input
                v-model.trim="form.morningTemp"
                autocomplete="off"
                placeholder="请输入体温"
                size="large"
                clearable
              />
            </el-form-item>

            <el-form-item label="中午体温" prop="afternoonTemp">
              <el-input
                v-model.trim="form.afternoonTemp"
                autocomplete="off"
                placeholder="请输入体温"
                size="large"
                clearable
              />
            </el-form-item>
            <el-form-item label="晚上体温" prop="nightTemp">
              <el-input
                v-model.trim="form.nightTemp"
                autocomplete="off"
                placeholder="请输入体温"
                size="large"
                clearable
              />
            </el-form-item>

            <el-form-item label="症状">
              <el-select
                v-model="form.symptom"
                class="m-2"
                placeholder="请选择症状"
                size="large"
                clearable
                filterable
              >
                <el-option
                  v-for="item in symptoms"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="近期所在地">
              <el-cascader
                placeholder="请选择所在地"
                size="large"
                :options="options"
                v-model="selectedOptions"
                @change="handleChange"
                clearable
                filterable
              >
              </el-cascader>
            </el-form-item>

            <el-form-item label="健康状态">
              <el-select
                v-model="form.healthStatus"
                class="m-2"
                placeholder="请选择健康状态"
                size="large"
                clearable
                filterable
              >
                <el-option
                  v-for="item in health"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="风险区">
              <el-select
                v-model="form.riskZone"
                class="m-2"
                placeholder="请选择所处风险区"
                size="large"
                clearable
                filterable
              >
                <el-option
                  v-for="item in riskZones"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save_info"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script>
import { serverIp } from '../../../public/config'

import { regionData, CodeToText, TextToCode } from 'element-china-area-data'

export default {
  // name: 'pagination-modul',
  name: 'HeathClockTable',
  data() {
    return {
      serverIp: serverIp,
      //中国省市区级
      options: regionData, //省市区数据
      selectedOptions: [], // 选中的地区
      tableData: [],

      //   分页器
      pageNum: 1,
      pageSize: 10,
      small: false,
      disabled: false,
      background: false,
      total: 0,

      // 分页查询-输入框
      username: '',
      phone: '',
      recentHome: '',

      provinceCode: '',
      cityCode: '',
      areaCode: '',

      // 弹窗
      dialogFormVisible: false,
      formLabelWidth: '100px',

      form: {
        // username: '',
        // sex: '',
        // age: '',
        // phone: '',
        // morningTemp: '',
        // afternoonTemp: '',
        // nightTemp: '',
        // symptom: '',
        // recentHome: '',
        // riskZone: '',
        // recentZone: '',
        // healthStatus: '',
        // provinceCode: '',
        // cityCode: '',
        // areaCode: ''
      },
      // 批量删除
      multipleSelection: [],

      //症状
      symptoms: [
        {
          value: '咳嗽',
          label: '咳嗽'
        },
        {
          value: '发烧',
          label: '发烧'
        },
        {
          value: '发烧咳嗽',
          label: '发烧咳嗽'
        },
        {
          value: '不发烧咳嗽',
          label: '不发烧咳嗽'
        },
        {
          value: '正常',
          label: '正常'
        },
        {
          value: '其他',
          label: '其他'
        }
      ],
      //风险区
      riskZones: [
        {
          value: '高风险',
          label: '高风险'
        },
        {
          value: '中风险',
          label: '中风险'
        },
        {
          value: '低风险',
          label: '低风险'
        }
      ],
      //健康状态
      health: [
        {
          value: '健康',
          label: '健康'
        },
        {
          value: '不健康',
          label: '不健康'
        }
      ],
      //表单效验
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            // 失去焦点
            trigger: 'blur'
          },
          {
            //最小最大值
            min: 2,
            max: 10,
            message: '长度至少3~10个字符',
            trigger: 'blur'
          }
        ],
        sex: [],
        age: [
          { required: true, message: '年龄不能为空' },
          { type: 'number', message: '年龄必须为数字值' }
        ],
        phone: [
          {
            validator: 'validatePhone',
            //必填项
            required: true,
            message: '请输入手机号',
            // 失去焦点
            trigger: 'blur'
          },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号码格式不正确',
            trigger: 'blur'
          }
        ],
        morningTemp: [
          { required: true, message: '温度不能为空' },
          { type: 'number', message: '温度必须为数字值' }
        ],

        afternoonTemp: [
          { required: true, message: '温度不能为空' },
          { type: 'number', message: '温度必须为数字值' }
        ],
        nightTemp: [
          { required: true, message: '温度不能为空' },
          { type: 'number', message: '温度必须为数字值' }
        ]
      }
    }
  },
  created() {
    // 请求分页查询的数据
    this.load()
    this.selectedOptions = [
      this.form.provinceCode,
      this.form.cityCode,
      this.form.areaCode
    ]
  },
  methods: {
    // 分页
    handleSizeChange(pageSize) {
      console.log('页数:' + pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log('每页的数据：' + pageNum)
      this.pageNum = pageNum
      this.load()
    },

    // 请求分页查询的数据
    load() {
      console.log(this.tab)

      this.$http
        .get('/healthclock/page', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            username: this.username,
            phone: this.phone
          }
        })
        .then((res) => {
          console.log('分页类型' + typeof res)
          console.log(res)
          this.tableData = res.data.records
          this.total = res.data.total
        })
    },
    // 重置
    clears() {
      this.username = ''
      this.phone = ''
      this.load()
    },
    // 弹窗
    handleadd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    // 新增数据
    save_info() {
      this.myref()
      var b = JSON.stringify(this.form)
      if (b != '{}') {
        this.$http.post('/healthclock', this.form).then((res) => {
          console.log(res)
          if (res.status == '200') {
            this.$message.success('保存成功')
            this.dialogFormVisible = false
            // 刷新页面数据

            this.load()
          }
        })
      } else {
        console.log('123')
        this.$message.error('保存失败')
      }
    },

    myref() {
      this.$refs['formRef'].validate((valid) => {
        console.log(valid)
      })
    },
    // 编辑
    handleEdit(row) {
      console.log(row)
      // 当前的值赋予到form对象中
      // row是proxy 需要转化为json
      console.log('编辑类型' + typeof row.recentHome)
      this.form = JSON.parse(JSON.stringify(row))
      console.log(this.form)
      this.handleTest(row)
      // this.handleTest(row)
      // this.form = JSON.parse(JSON.stringify(row));
      // 打开弹窗
      this.dialogFormVisible = true
    },
    // 删除
    del(id) {
      this.$http.delete('/healthclock/' + id).then((res) => {
        if (res.data) {
          this.$message.success('删除成功')
          // 刷新页面数据
          this.load()
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 批量删除
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      // 对象数组变成 纯id的数组
      let ids = this.multipleSelection.map((v) => v.id) //[{},{},{}]=>[1,2,3]
      console.log(ids)

      this.$http.delete('/healthclock/del/batch', { data: ids }).then((res) => {
        if (res.data) {
          this.$message.success('批量删除成功')
          // 刷新页面数据
          this.load()
        } else {
          this.$message.error('批量删除失败')
        }
      })
    },
    // 导出文件
    exp() {
      // alert('123')
      console.log('导出文件中')
      window.open(`http://${serverIp}:9090/healthclock/export`)
    },
    // 导入文件
    //成功
    handleExcelImportSuccess() {
      this.$message.success('导入成功')
      this.load()
    },
    //失败
    handleExcelImportError() {
      this.$message.error('导入失败')
      this.load()
    },

    myclear() {
      console.log('清理中')
    },

    //初始化省市
    handleChangeOne(value) {
      console.log(value)
      if (value != null) {
        console.log(value)
        console.log(
          CodeToText[value[0]],
          CodeToText[value[1]],
          CodeToText[value[2]]
        )
        this.provinceCode = value[0]
        this.cityCode = value[1]
        this.areaCode = value[2]
        this.recentHome =
          CodeToText[value[0]] +
          '/' +
          CodeToText[value[1]] +
          '/' +
          CodeToText[value[2]]
        console.log('页面选择:' + this.recentHome)
      } else {
        this.recentHome = ''
        console.log('当前地址为空：' + this.recentHome)
      }
    },

    //初始化省市
    handleChange(value) {
      console.log(value)
      if (value != null) {
        console.log(value)
        console.log(
          CodeToText[value[0]],
          CodeToText[value[1]],
          CodeToText[value[2]]
        )
        this.form.provinceCode = value[0]
        this.form.cityCode = value[1]
        this.form.areaCode = value[2]
        this.form.recentHome =
          CodeToText[value[0]] +
          '/' +
          CodeToText[value[1]] +
          '/' +
          CodeToText[value[2]]
        console.log('页面选择:' + this.form.recentHome)
      } else {
        this.form.recentHome = ''
      }
    },
    //回显 （获取数据库的省市）
    handleTest(newdata) {
      console.log('!2313')
      if (newdata.recentHome != '') {
        var str = newdata.recentHome + ''
        var index = str.indexOf('/')
        var last = str.lastIndexOf('/')
        var provinceCode = TextToCode[str.slice(0, index)].code
        var cityCode =
          TextToCode[str.slice(0, index)][str.slice(index + 1, last)].code
        var areaCode =
          TextToCode[str.slice(0, index)][str.slice(index + 1, last)][
            str.slice(last + 1)
          ].code
        this.selectedOptions = [provinceCode, cityCode, areaCode]
        console.log('数据库' + this.selectedOptions)
      } else {
        this.selectedOptions = []
        console.log('数据库为空' + this.selectedOptions)
      }
    },
    filterTag(value, row) {
      return row.tag === value
    }
  }
}
</script>
  
  <style lang="less" scoped>
// 分页
.demo-pagination-block {
  padding: 10px;
}
.upload_file {
  display: inline-flex;
  /deep/ .el-upload{
    display: block !important;
  }
}

// .user_table {
//   overflow: hidden;
// }
// /deep/.el-table__body-wrapper .el-scrollbar__bar {
//   // overflow: hidden;
//   z-index: -1;
// }
</style>